package cn.newgrand.netcall.ui.leaveword;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.component.TitlePanel;
import org.jivesoftware.spark.component.tabbedPane.SparkTab;
import org.jivesoftware.spark.component.tabbedPane.SparkTabbedPane;
import org.jivesoftware.spark.component.tabbedPane.SparkTabbedPaneListener;
import org.jivesoftware.spark.ui.ChatRoom;
import org.jivesoftware.spark.ui.ContainerComponent;


public class ManagerLeavewordPanel extends SparkTabbedPane{

	private static final long serialVersionUID = 1L;
	private JOptionPane pane;
	private JDialog dlg;
    TitlePanel titlePanel;
    private Map<String, LeavewordPanel> leavewordPanels = new HashMap<String, LeavewordPanel>();
	//final JTabbedPane tabbedPane = new JTabbedPane();
	//final SparkTabbedPane sparkTabbedPane = new SparkTabbedPane();
    
    private static ManagerLeavewordPanel instance;
    
    public synchronized static ManagerLeavewordPanel getInstance(){
    	if(instance == null){
    		instance = new ManagerLeavewordPanel();
    	}
    	return instance;
    }
	
	public ManagerLeavewordPanel(){
		
		 // Set minimum size
        setMinimumSize(new Dimension(450, 350));
        // Don't allow tabs to shrink and allow scrolling.

        setCloseButtonEnabled(true);
		
        addSparkTabbedPaneListener(new SparkTabbedPaneListener() {
            public void tabRemoved(SparkTab tab, Component component, int index) {
               if (component instanceof ContainerComponent) {
                    ((ContainerComponent)component).closing();
                }
            }

            public void tabAdded(SparkTab tab, Component component, int index) {
//                stateChanged(null);
            }

            public void tabSelected(SparkTab tab, Component component, int index) {
//                stateChanged(null);
                // Notify ChatRoomListeners that the tab has been activated.
                if (component instanceof ChatRoom) {
//                    fireChatRoomActivated((ChatRoom)component);
                    //TODO 和上面一段代码替换一下位置以后，切换chatroom保持聊天输入窗不再有效
//                    ((ChatRoom)component).resizePreferSizeToLast();
                }
            }

            public void allTabsRemoved() {
//                chatFrame.setTitle("");
//                chatFrame.setVisible(false);
//                chatFrame.setState(Frame.NORMAL);
//                chatFrame.dispose();
            }


            public boolean canTabClose(SparkTab tab, Component component) {
                return true;
            }
        });

        createDialog();
	}
	
	private void createDialog(){
		ImageIcon icon = null;
        if (icon == null) {
            icon = SparkRes.getImageIcon(SparkRes.BLANK_24x24);
        }
        // Create the title panel for this dialog
        titlePanel = new TitlePanel("咨询者的留言", "您可以选择性的回复", icon, true);

        // Construct main panel w/ layout.
        final JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
//        mainPanel.add(titlePanel, BorderLayout.NORTH);

        // The user should only be able to close this dialog.
//        Object[] options = {Res.getString("save"), Res.getString("cancel")};
//        pane = new JOptionPane(this, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, options, options[0]);

        mainPanel.add(this, BorderLayout.CENTER);

        JOptionPane p = new JOptionPane();
        dlg = p.createDialog(SparkManager.getWorkspace(), "留言板");
        dlg.addWindowListener(new WindowAdapter() {
        	public void windowClosing(WindowEvent windowEvent) {
            	if(getTabCount() > 1){
            		if(JOptionPane.showConfirmDialog(dlg, "是否确认关闭已打开的"+getTabCount()+"个聊天窗口", "关闭窗口", JOptionPane.YES_NO_OPTION) != 0){
                		return;
                	}
            	}
                // Save layout
            	closeAllContainerComponent(getTabCount());
            	dlg.setVisible(false);
            }
		});
        dlg.setModal(false);
        
        dlg.pack();
        dlg.setSize(588, 500);
        dlg.setResizable(true);
        dlg.setContentPane(mainPanel);
        dlg.setLocationRelativeTo(SparkManager.getWorkspace());

//        PropertyChangeListener changeListener = new PropertyChangeListener() {
//            public void propertyChange(PropertyChangeEvent e) {
//                String value = (String)pane.getValue();
//                if (Res.getString("cancel").equals(value)) {
//                    pane.removePropertyChangeListener(this);
//                    //dlg.dispose();
//                    dlg.setVisible(false);
//                }
//            }
//
//        };
//
//        pane.addPropertyChangeListener(changeListener);
        dlg.setVisible(true);
        dlg.toFront();
        dlg.requestFocus();
	}
	
	public void addContainerComponent(LeavewordPanel comp){
		if(isHasLeavewordPanel(comp.getAskerJid())){
			return;
		}
		if(!dlg.isVisible()){
			dlg.setVisible(true);
		}
		addTab(comp.getTabTitle(), comp.getTabIcon(), comp.getGUI(), "ly");
		leavewordPanels.put(comp.getAskerJid(), comp);
	}
	
	public boolean isHasLeavewordPanel(String askerJid){
		return leavewordPanels.containsKey(askerJid);
	}
	
	
	public void closeTab(Component component) {
        int location = indexOfComponent(component);
        if (location == -1) {
            return;
        }

        this.removeTabAt(location);
        
        if (getTabCount() == 0 && dlg.isVisible()) {
        	dlg.setVisible(false);
         }
    }
	
	public void closeLeavewordPanel(LeavewordPanel leavewordPanel){
		if(!isHasLeavewordPanel(leavewordPanel.getAskerJid())){
			return;
		}
		int location = indexOfComponent(leavewordPanel);
        if (location == -1) {
            return;
        }

        this.removeTabAt(location);
        leavewordPanels.remove(leavewordPanel.getAskerJid());
        leavewordPanel = null;
        if (getTabCount() == 0 && dlg.isVisible()) {
        	dlg.setVisible(false);
         }
	}
	
	public LeavewordPanel getLeavewordPanel(String askerJid){
		if(isHasLeavewordPanel(askerJid)){
			return leavewordPanels.get(askerJid);
		}
		return null;
	}
	
    public void closeAllContainerComponent(int tabCount) {
    	List<Component> components = new ArrayList<Component>();
        for (int i = 0; i < tabCount; i++) {
            Component comp = getComponentAt(i);
            if (comp instanceof ContainerComponent) {
            	components.add(comp);
                //((ContainerComponent)comp).closing();
            }
        }
        for (Component containerComponent : components) {
        	//closeTab(containerComponent);
        	if(containerComponent instanceof LeavewordPanel){
        		closeLeavewordPanel((LeavewordPanel)containerComponent);
        	}
		}
    }

}
